package com.example.demo.servlet;

import com.example.demo.common.AjaxResult;
import com.example.demo.common.AppVariable;
import com.example.demo.common.PassWordUtils;
import com.example.demo.entity.Userinfo;
import com.example.demo.service.UserService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private static final Logger logger = Logger.getLogger(LoginServlet.class);
    @Autowired
    private UserService userService;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        

        Userinfo userinfo = userService.getUserByName(username);
        
        if (userinfo != null) {
            Cookie cookie = new Cookie("userinfo", Integer.toString(userinfo.getId()));
            cookie.setMaxAge(1 * 60 * 60);
            resp.addCookie(cookie);
            req.setAttribute("userinfoaccount", userinfo.getId());

        } else {
            req.getRequestDispatcher("toadminlogin").forward(req, resp);
        }
    }
}
